package com.example.crossoriginserver.filter;

import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤每个请求，支持跨域
 * @author wanghaiyang
 * @date 2018/4/9 14:49
 */
public class CrossOriginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        String origin = httpServletRequest.getHeader("Origin");
//        httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");

        if (!StringUtils.isEmpty(origin)) {
            /**
             * 带cookie的请求，origin必须是全匹配，不能使用*
             */
            httpServletResponse.addHeader("Access-Control-Allow-Origin", origin);
        }
        /**
         * 带cookie的请求,必须设置Access-Control-Allow-Credentials为true
         */
        httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.addHeader("Access-Control-Allow-Methods", "*");


        /**
         * 获取请求头
         * Access-Control-Request-Headers与设置的允许请求头Access-Control-Allow-Headers不是同一个key
         * Access-Control-Request-Headers请求头
         * Access-Control-Allow-Headers允许请求头
         */
        String headers = httpServletRequest.getHeader("Access-Control-Request-Headers");
        /**
         * 支持自定义header
         */
        if (!StringUtils.isEmpty(headers)) {
            httpServletResponse.addHeader("Access-Control-Allow-Headers", headers);
        }

        /**
         * 缓存options请求
         */
        httpServletResponse.addHeader("Access-Control-Max-Age", "3600");





        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    @Override
    public void destroy() {

    }
}
